package com.heima.fremarker.template;

import com.alibaba.fastjson.JSONArray;
import com.heima.file.MinIoTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class FreemarkerTemplate {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIoTemplate minIoTemplate;

    /**
     * 生成静态文件
     * @param content
     * @return
     */
    public InputStream generate(String content) throws IOException, TemplateException {
        //指定模板文件
        Template template = configuration.getTemplate("article.ftl");
        //完成文本的格式转换
        Map<String,Object> params = new HashMap<>();
        params.put("content", JSONArray.parseArray(content));
        // 将数据转换成流文件
        StringWriter stringWriter = new StringWriter();
        template.process(params,stringWriter);
        return new ByteArrayInputStream(stringWriter.toString().getBytes());
    }

    // 生成静态文件
    public String generateAndUpload(String content,String fileName) throws IOException, TemplateException {
        InputStream generate = generate(content);
        return minIoTemplate.uploadFile("",fileName,generate,"html");
    }





}
